package com.cjz.roomdbdemo.db;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.AsyncTask;

import java.util.List;

/**
 * 使用这个类隔离UI与数据库
 * <p>
 * NoteRepository 与 DAO 打交道的时候必须切换线程！强制要求的，否则报错
 * <p>
 * 注意以下3个接口 getAllNotes 、 insert、deleteAll， 其中getAllNotes 表面上看并没有在AsyncTask执行，实际上 LiveData 自动在后台线程的异步执行了query
 * <p>
 * <p>
 * Created by cjz on 2018/8/31.
 *
 * @see <a href="https://codelabs.developers.google.com/codelabs/android-room-with-a-view/?hl=zh-cn#6">参考资料：Add a Room database</a>
 */
public class NoteRepository {

    private NoteDAO noteDAO;
    private LiveData<List<Note>> allNotes;

    public NoteRepository(Application application) {
        NoteDatabase db = NoteDatabase.getDatabase(application);
        noteDAO = db.noteDao();
        allNotes = noteDAO.getAllNotes();
    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }

    public void insert(Note note) {
        new InsertAsyncTask(noteDAO).execute(note);
    }

    public void deleteAll() {
        new DeleteAllAsyncTask(noteDAO).execute();
    }


    private static class InsertAsyncTask extends AsyncTask<Note, Void, Void> {

        private NoteDAO noteDAO;

        InsertAsyncTask(NoteDAO dao) {
            noteDAO = dao;
        }

        @Override
        protected Void doInBackground(Note... notes) {
            noteDAO.insert(notes[0]);
            return null;
        }
    }

    private static class DeleteAllAsyncTask extends AsyncTask<Note, Void, Void> {
        private NoteDAO noteDAO;

        DeleteAllAsyncTask(NoteDAO dao) {
            noteDAO = dao;
        }

        @Override
        protected Void doInBackground(Note... notes) {
            noteDAO.deleteAll();
            return null;
        }
    }
}
